package com.ruiysoft.controller.upload.pic;


import com.google.gson.Gson;
import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.model.DefaultPutRet;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author Yanghu
 * @since 2018-08-20
 */
@RestController
@RequestMapping("qiniu")
@CrossOrigin
public class QinuController {
    private static final Logger log = LoggerFactory.getLogger(QinuController.class);

//    //构造一个带指定Zone对象的配置类
//    Configuration cfg = new Configuration(Zone.zone0());
//    //...其他参数参考类注释
//    UploadManager uploadManager = new UploadManager(cfg);
//
//    String accessKey = "cd49_Oa7kxvx8ebzyqSQmBG8ISYTJTp5Vi6e284t";
//    String secretKey = "3WJoNPdOGHDiFCzV358uPqiBozEo0bKjEel94t8h";
//    String bucket = "shop";
//
//    Auth auth = Auth.create(accessKey, secretKey);
//
//    //String localFilePath = "/Users/liudh/Desktop/WechatIMG383.jpeg";
//    //默认不指定key的情况下，以文件内容的hash值作为文件名
//    String key = null;
    @Resource
    QinuService qinuService;

    @PostMapping("upload")
    public Object upload(@RequestParam("file") MultipartFile file) {
        log.debug("upload api is invoked..");
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("success", false);
        try {
            Response response = qinuService.upload(file);
            //解析上传成功的结果
            DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
            System.out.println(putRet.key);
            System.out.println(putRet.hash);

            map.put("success", true);
            map.put("downloadPath", "http://media.avicyt.com/" + putRet.key);

        } catch (QiniuException ex) {
            log.error("qiniu error",ex);
            Response r = ex.response;
            map.put("errorMsg", r.toString());
        } catch (IOException e) {
            log.error("upload file error",e);
        }
        return map;
    }




}
